@file:Suppress("unused")

package com.hjh.tool.util

import android.app.ActivityManager
import android.content.Context
import android.os.Debug
import android.os.Environment
import android.os.Process
import android.os.StatFs
import com.elvishew.xlog.XLog
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
import kotlin.also
import kotlin.collections.dropLastWhile
import kotlin.collections.isNotEmpty
import kotlin.collections.toTypedArray
import kotlin.io.use
import kotlin.text.format
import kotlin.text.isEmpty
import kotlin.text.split
import kotlin.text.startsWith
import kotlin.text.toInt
import kotlin.text.toRegex


/**
 * @author： hjh
 * @createDate： 2025/4/15 16:54
 * @description：
 * @qq： 3472903821
 * @version: 1.0
 */
object HardwareInfoUtil {

    /**
     * 当前的手机总存储内存大小
     *
     * @return xx GB
     */
    fun getTotalInternalMemorySize(): String {
        val path = Environment.getDataDirectory()
        val stat = StatFs(path.path)
        val blockSize = stat.blockSizeLong
        val totalBlocks = stat.blockCountLong
        return formatFileSize(totalBlocks * blockSize)
    }

    /**
     * 当前手机可用存储内存大小
     *
     * @return xx GB
     */
    fun getAvailableInternalMemorySize(): String {
        val path = Environment.getDataDirectory()
        val stat = StatFs(path.path)
        val blockSize = stat.blockSizeLong
        val availableBlocks = stat.availableBlocksLong
        return formatFileSize(availableBlocks * blockSize)
    }

    /**
     * 获取android总运行内存大小
     */
    fun getTotalMemory(): String {
        val str1 = "/proc/meminfo" // 系统内存信息文件
        val str2: String
        val arrayOfString: Array<String>
        var initialMemory: Long = 0
        try {
            val localFileReader = FileReader(str1)
            val localBufferedReader = BufferedReader(localFileReader, 8192)
            str2 = localBufferedReader.readLine() // 读取 memInfo 第一行，系统总内存大小
            arrayOfString =
                str2.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            for (num in arrayOfString) {
                XLog.i("$str2, $num + \t")
            }
            // 获得系统总内存，单位是KB
            val i = arrayOfString[1].toInt()
            // int值乘以1024转换为long类型
            initialMemory = i.toLong() * 1024
            localBufferedReader.close()
        } catch (e: IOException) {
            XLog.d("${e.message}")
        }
        return formatFileSize(initialMemory) // Byte转换为KB或者MB，内存大小规格化
    }

    /**
     * 获取android当前可用运行内存大小
     * @param context
     */
    fun getAvailMemory(context: Context): String {
        val mi = ActivityManager.MemoryInfo()
        (context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager).getMemoryInfo(mi)
        // mi.availMem; 当前系统的可用内存
        return formatFileSize(mi.availMem) // 将获取的内存大小规格化
    }

    /**
     * 获取当前应用使用的内存大小
     *
     * @return 单位 MB
     */
    private fun sampleMemory(context: Context): Double {
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        var mem = 0.0
        try {
            val memInfo: Array<Debug.MemoryInfo> = activityManager.getProcessMemoryInfo(
                intArrayOf(
                    Process.myPid()
                )
            )
            if (memInfo.isNotEmpty()) {
                val totalPss: Int = memInfo[0].totalPss
                if (totalPss >= 0) {
                    mem = totalPss / 1024.0
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return mem
    }


    /**
     * CPU 主频
     *
     * @return 单位 MHz
     */
    fun getCPUFrequency(): String {
        var line: String
        val cpuFreq = StringBuilder()
        try {
            BufferedReader(FileReader("/proc/cpuinfo")).use { reader ->
                while ((reader.readLine().also { line = it }) != null) {
                    if (line.startsWith("BogoMIPS") || line.startsWith("cpu MHz")) {
                        cpuFreq.append(line).append("\n")
                    }
                }
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return cpuFreq.toString()
    }

    private fun formatFileSize(sizeBytes: Long): String {
        return when {
            sizeBytes < 1024 -> "$sizeBytes B"
            sizeBytes < 1024 * 1024 -> "${"%.1f".format(sizeBytes / 1024.0)} KB"
            sizeBytes < 1024 * 1024 * 1024 -> "${"%.1f".format(sizeBytes / (1024.0 * 1024))} MB"
            else -> "${"%.1f".format(sizeBytes / (1024.0 * 1024 * 1024))} GB"
        }
    }
}